package com.xiaotao.realtimeui.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaotao.realtimeui.controller.WsController;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@Data
@AllArgsConstructor
class Info {
    private String id;
    private Long value;
}
@Component
public class WsSender {
    @Resource
    private WsController wsController;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final static String KEY_PREFIX = "bussiness::order::total::" ;
    private final static String KEY_PREFIX_PATTERN = "bussiness::order::total::*" ;

    @Scheduled(cron = "0/1 * * * * ?")
    public void sendMsg() {
        Set<String> keys = redisTemplate.keys(KEY_PREFIX_PATTERN);
        if (keys == null) {
            System.out.println("无key");
            return;
        }
        try {
            List<Info> res = new LinkedList<>();
            for (String key : keys) {
                Integer v = (Integer)redisTemplate.opsForValue().get(key);

                res.add(new Info(key.substring(KEY_PREFIX.length()), v.longValue()));
            }
            wsController.sendMsg(objectMapper.writeValueAsString(res));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
